//Design a simplified version of Twitter where users can post tweets, follow/unf
//ollow another user, and is able to see the 10 most recent tweets in the user's n
//ews feed. 
//
// Implement the Twitter class: 
//
// 
// Twitter() Initializes your twitter object. 
// void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId 
//by the user userId. Each call to this function will be made with a unique tweetI
//d. 
// List<Integer> getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs 
//in the user's news feed. Each item in the news feed must be posted by users who 
//the user followed or by the user themself. Tweets must be ordered from most rece
//nt to least recent. 
// void follow(int followerId, int followeeId) The user with ID followerId start
//ed following the user with ID followeeId. 
// void unfollow(int followerId, int followeeId) The user with ID followerId sta
//rted unfollowing the user with ID followeeId. 
// 
//
// 
// Example 1: 
//
// 
//Input
//["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", 
//"unfollow", "getNewsFeed"]
//[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
//Output
//[null, null, [5], null, null, [6, 5], null, [5]]
//
//Explanation
//Twitter twitter = new Twitter();
//twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
//twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 twe
//et id -> [5]. return [5]
//twitter.follow(1, 2);    // User 1 follows user 2.
//twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
//twitter.getNewsFeed(1);  // User 1's news feed should return a list with 2 twe
//et ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted afte
//r tweet id 5.
//twitter.unfollow(1, 2);  // User 1 unfollows user 2.
//twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 twe
//et id -> [5], since user 1 is no longer following user 2.
// 
//
// 
// Constraints: 
//
// 
// 1 <= userId, followerId, followeeId <= 500 
// 0 <= tweetId <= 104 
// All the tweets have unique IDs. 
// At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unf
//ollow. 
// 
// Related Topics 堆 设计 哈希表 
// 👍 214 👎 0


package leetcode.editor.cn;

import java.util.*;

//Java：Design Twitter
class P355DesignTwitter {
    public static void main(String[] args) {
        // TO TEST
        Twitter twitter = new P355DesignTwitter().new Twitter();
        twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
        twitter.postTweet(1, 3); // User 1 follows user 2.
        twitter.postTweet(1, 101); // User 1 follows user 2.
        twitter.postTweet(1, 13); // User 1 follows user 2.
        twitter.postTweet(1, 10); // User 1 follows user 2.
        twitter.postTweet(1, 2); // User 1 follows user 2.
        twitter.postTweet(1, 94); // User 1 follows user 2.
        twitter.postTweet(1, 505); // User 1 follows user 2.
        twitter.postTweet(1, 333); // User 1 follows user 2.
        twitter.postTweet(1, 22); // User 1 follows user 2.
        twitter.postTweet(1, 11); // User 1 follows user 2.
        System.out.println(twitter.getNewsFeed(1));  // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
    }
    //leetcode submit region begin(Prohibit modification and deletion)
    class Twitter {

        /**
         * Initialize your data structure here.
         */
        Map<Integer, TreeSet<Integer>> fans;
        Map<Integer, TweetNode> tweet;
        int last = 0;

        public Twitter() {
            fans = new HashMap<>();
            tweet = new LinkedHashMap<>();
        }

        class TweetNode implements Comparable<TweetNode> {
            int tweetId;
            long time;
            TweetNode next;

            TweetNode(int tweetId) {
                this.tweetId = tweetId;
                time = last++;
            }

            @Override
            public int compareTo(TweetNode o2) {
                return this.time - o2.time == 0 ? 0 : (this.time - o2.time > 0 ? -1 : 1);
            }
        }

        /**
         * Compose a new tweet.
         */
        public void postTweet(int userId, int tweetId) {
            tweet.compute(userId, (key, value) -> {
                if (value == null) {
                   return new TweetNode(tweetId);
                }else{
                    TweetNode tweetNode = new TweetNode(tweetId);
                    tweetNode.next = value;
                    return tweetNode;
                }
            });

        }

        /**
         * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
         */
        public List<Integer> getNewsFeed(int userId) {
            TreeSet<Integer> fanSet = fans.getOrDefault(userId, new TreeSet<>());
            fanSet.add(userId);
            TreeSet<TweetNode> newsFeed = new TreeSet<>();
            List<Integer> result = new ArrayList<>();
            for (Integer fan : fanSet) {
                if (this.tweet.containsKey(fan)) {
                   TweetNode tweet = this.tweet.get(fan);
                    newsFeed.add(tweet);
                }
            }
            while (!newsFeed.isEmpty()) {
                TweetNode tweetNode = newsFeed.pollFirst();
                if (result.size() == 10) {
                    break;
                }
                result.add(tweetNode.tweetId);
                if (tweetNode.next != null) {
                    newsFeed.add(tweetNode.next);
                }

            }
            return result;
        }

        /**
         * Follower follows a followee. If the operation is invalid, it should be a no-op.
         */
        public void follow(int followerId, int followeeId) {
            fans.compute(followerId, (key, value) -> {
                if (value == null) {
                    value = new TreeSet<>();
                }
                value.add(followeeId);
                return value;
            });
        }

        /**
         * Follower unfollows a followee. If the operation is invalid, it should be a no-op.
         */
        public void unfollow(int followerId, int followeeId) {
            fans.compute(followerId, (key, value) -> {
                if (value == null) {
                    return null;
                }
                value.remove(followeeId);
                return value;
            });
        }
    }

/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter obj = new Twitter();
 * obj.postTweet(userId,tweetId);
 * List<Integer> param_2 = obj.getNewsFeed(userId);
 * obj.follow(followerId,followeeId);
 * obj.unfollow(followerId,followeeId);
 */
//leetcode submit region end(Prohibit modification and deletion)

}